package de.pyranja.storage;

import static java.nio.file.FileVisitResult.CONTINUE;
import static java.nio.file.FileVisitResult.TERMINATE;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;

import org.junit.After;

import com.google.common.base.Charsets;
import com.google.common.io.ByteStreams;
import com.google.common.io.InputSupplier;

/*
 * provides helper values and functions for file based blob persistence tests
 */
public class BlobFixture {

	public static final String TEST_DIR = "D:/Playground/blobs";
	
	protected static final InputSupplier<? extends InputStream> PAYLOAD = ByteStreams
				.newInputStreamSupplier("TEST_PAYLOAD".getBytes(Charsets.UTF_8));
	protected static final InputSupplier<? extends InputStream> ANOTHER = ByteStreams
			.newInputStreamSupplier("ANOTHER_PAYLOAD".getBytes(Charsets.UTF_8));
	
	@After
	public void tearDown() throws IOException {
		final File root = new File(TEST_DIR);
		// clear test directory
		Files.walkFileTree(root.toPath(), new SimpleFileVisitor<Path>() {
			@Override
			public FileVisitResult visitFile(Path file,
					BasicFileAttributes attrs) throws IOException {
				Files.delete(file);
				return CONTINUE;
			}
	
			@Override
			public FileVisitResult postVisitDirectory(Path dir, IOException exc)
					throws IOException {
				if (Files.isSameFile(dir, root.toPath())) {
					return TERMINATE;
				}
				if (exc == null) {
					Files.delete(dir);
					return CONTINUE;
				} else {
					throw exc;
				}
			}
		});
	}
}
